package chatServer

import "fmt"

type Message chan string

type Room struct {
	id       string
	agents   map[int64]*Agent
	maxAgent int
	joining  chan *Agent
	leaving  chan *Agent
	message  Message
}

func NewRoom() (room *Room) {

	room = &Room{id:"root", agents:make(map[int64]*Agent), joining:make(chan *Agent), leaving:make(chan *Agent),message:make(Message)}
	go room.listen()
	return room;
}

func (room Room) listen() {
	for {
		select {
		case join := <-room.joining:
			room.accept(join)

		case leave := <-room.leaving:
			room.kickOff(leave)

		case message := <-room.message:
			room.msgToAll(message)
		}
	}
}

func (room *Room) accept(agent *Agent) {
	fmt.Printf("%d 进入房间 %s", agent.uuid, room.id)
	room.agents[agent.uuid] = agent

}

func (room *Room) msgToAll(message string) {
	fmt.Println("发消息给所有用户")
	for _, value := range room.agents {
		value.out <- message
	}
}

func (room *Room) kickOff(agent *Agent) {
	fmt.Printf("%s 离开房间 %s", agent.uuid, room.id)
	delete(room.agents, agent.uuid)
}
